﻿using Model;
using System;
using System.Collections.Generic;
using DBHelper;

namespace ZoneLine
{
    internal class PlcAddrInfoViewModel : ViewModelBase
    {
        #region MyRegion
        private t_PlcAddr _CurrModel;
        private t_PlcAddr currModelbak;
        private t_PlcAddr _SelectedModel;
        private List<t_Plc> _plcList;
        private string _cmdNum;
        #endregion
        public PlcAddrInfoViewModel(t_PlcAddr model)
        {
            if (model == null)
            {
                model = new t_PlcAddr();
               // model.Plc = new t_Plc();
             }
            currModelbak = model;
            PlcList = DbContext.GetModels<t_Plc>("1=1");
            SelectedModel = currModelbak.Clone<t_PlcAddr>();

            IsAddMode = SelectedModel.ID == 0;

        }

        public override bool Init()
        {
            return true;
        }

        public t_PlcAddr SelectedModel { get => _SelectedModel; set => Set(ref _SelectedModel, value); }
        public t_PlcAddr CurrModel
        {
            get => _CurrModel;
            set => Set(ref _CurrModel, value);
        }
        public List<t_Plc> PlcList { get => _plcList; set => Set(ref _plcList, value); }

        /// <summary>
        /// 编辑模式
        /// </summary>
        public bool IsAddMode { get; set; } = false;
        /// <summary>
        /// 命令码
        /// </summary>
        public string CmdNum { get =>_cmdNum; set=>Set(ref _cmdNum,value);}

        #region Command

        #region SaveCmd
        private RelayCommand saveCmd;
        public RelayCommand SaveCmd => saveCmd ?? (saveCmd = new RelayCommand(Save, CanSave));

        private void Save()
        {
            try
            {
                bool rlt = false;
                if (IsAddMode)
                {
                    rlt = DbContext.AddModel(SelectedModel);
                }
                else
                {
                    // diffModel = CurrModel.GetChangedModel(currModelbak);
                    rlt = DbContext.UpdateModel(SelectedModel, currModelbak);
                }
                ShowMsg(rlt ? "保存成功！" : "保存失败，请查阅Logs！");
            }
            catch (Exception ex)
            {
             
                ShowMsg("保存失败，请查阅Logs！");
            }
        }

        private bool CanSave()
        {
            return SelectedModel.Validate();
        }
        #endregion

       

        #endregion
    }
}
